package gui.overview;

import gui.editrecipe.EditRecipe;
import gui.showrecipe.ShowRecipe;
import gui.tables.OverviewTable;

import javax.swing.ImageIcon;
import javax.swing.JPanel;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.HeadlessException;

import javax.swing.JButton;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;

import javax.swing.border.TitledBorder;

import org.jdom.JDOMException;

import start.Config;
import start.Start;

import xml.XMLRecipeReader;
import xml.XMLRecipeSaver;

/**
 * Panel zur Rezeptverwaltung.
 * Beinhaltet eine Uebersichtstabelle und eine Rezeptvorschau,
 * außerdem Buttons zur weiteren Interaktion.
 * @author Dennis Wittkoetter
 * 
 */
public class OverviewPanel extends JPanel {
	//Daten-Objekte
	/**ID zur Serialisierung*/
	private static final long serialVersionUID = 1L;
	/**XML-Saver zum Speichern von Rezepten*/
	private static XMLRecipeSaver xmlsaver;
	/**XML-Reader zum Lesen von Rezepten*/
	private static XMLRecipeReader xmlreader;
	/**Tabelle zur Rezeptuebersicht*/
	private final static OverviewTable table = new OverviewTable();

	//Layout-Objekte
	/**Vorschau-Panel*/
	private JPanel previewPanel;
	/**Button zum Oeffnen der Tabellenauswahl*/
	private final JButton btnOpenChoice = new JButton("Öffnen", new ImageIcon(Start.getImgs().getOpenSmall()));
	/**Button zum Bearbeiten der Tabellenauswahl*/
	private final JButton btnEditChoice = new JButton("Bearbeiten",new ImageIcon(Start.getImgs().getEditSmall()));
	/**Button zum Loeschen der Tabellenauswahl*/
	private final static JButton btnDeleteChoice = new JButton("Markierte löschen", new ImageIcon(Start.getImgs().getTrashSmall()));
	
	/**
	 * Konstruiert das Panel fuer die Rezept-Uebersicht
	 * @throws IOException 
	 * @throws JDOMException 
	 */
	public OverviewPanel() throws JDOMException, IOException {
		xmlsaver = new XMLRecipeSaver(Start.getRezeptexml());
		xmlreader = new XMLRecipeReader(Start.getRezeptexml());

		/**Layout einstellen*/
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{0, 0, 0, 200, 200, 0};
		gridBagLayout.rowHeights = new int[]{0, 0, 0};
		gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
		setLayout(gridBagLayout);
		
		/**Panel zu Kapselung der Tabelle erstellen*/
		JPanel tablePanel = table.buildPanel();
		tablePanel.setToolTipText("Hier siehst du alle Rezepte die du angelgt hast");
		table.updateFromXML(xmlreader);
		tablePanel.setBorder(new TitledBorder(null, "Rezepte", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		GridBagConstraints gbc_tablePanel = new GridBagConstraints();
		gbc_tablePanel.gridwidth = 4;
		gbc_tablePanel.insets = new Insets(10, 0, 5, 5);
		gbc_tablePanel.fill = GridBagConstraints.BOTH;
		gbc_tablePanel.gridx = 0;
		gbc_tablePanel.gridy = 0;
		add(tablePanel, gbc_tablePanel);
		
		/**JPanel fuer Rezeptvorschau aus OverviewPanel_Preview konstruieren*/
		buildPreviewPanel();
		
		table.getTable().addMouseListener(new MouseListener() {
			@Override public void mouseClicked(MouseEvent arg0) {
				try {
					rebuildPreviewPanel();
                	if (arg0.getButton()==MouseEvent.BUTTON1 
                	&&  arg0.getClickCount()==2 
                	&& !arg0.isConsumed()) {
                		arg0.consume();
                		new ShowRecipe(table.getTable().getSelectedRow(), 0);
                	}
				} catch (JDOMException e1) {
					e1.printStackTrace();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			@Override public void mouseEntered(MouseEvent arg0) {}
			@Override public void mouseExited(MouseEvent arg0) {}
			@Override public void mousePressed(MouseEvent arg0) {}
			@Override public void mouseReleased(MouseEvent arg0) {}
		});
		table.getTable().addKeyListener(new KeyListener() {
			@Override public void keyTyped(KeyEvent arg0) {}
			@Override public void keyPressed(KeyEvent arg0) {}
			@Override public void keyReleased(KeyEvent arg0) {
				try {
					rebuildPreviewPanel();
				} catch (JDOMException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}			
		});
		
		/**Button zum loeschen einer Listenauswahl konstruieren*/
		btnDeleteChoice.setEnabled(false);
		btnDeleteChoice.setToolTipText("Löscht die ausgewählten Rezepte");
		GridBagConstraints gbc_btnDeleteChoice = new GridBagConstraints();
		gbc_btnDeleteChoice.insets = new Insets(0, 0, 0, 5);
		gbc_btnDeleteChoice.gridx = 0;
		gbc_btnDeleteChoice.gridy = 1;
		add(btnDeleteChoice, gbc_btnDeleteChoice);
		btnDeleteChoice.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent arg0) {				
				//Dann Textinformationen
				try {
					table.removeCheckedEntries(xmlsaver);
					table.updateFromXML(xmlreader);
					rebuildPreviewPanel();
				} catch (JDOMException e) {
					if(Config.debugMode()) e.printStackTrace();
				} catch (IOException e) {
					if(Config.debugMode()) e.printStackTrace();
				}
			}
		});
		btnDeleteChoice.addKeyListener(new KeyListener() {
			@Override public void keyPressed(KeyEvent e) {
				try {
					if (e.getKeyCode() == KeyEvent.VK_ENTER) {
						table.removeCheckedEntries(xmlsaver);
						table.updateFromXML(xmlreader);
						rebuildPreviewPanel();
					}
				} catch (JDOMException e1) {
					e1.printStackTrace();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			@Override public void keyReleased(KeyEvent e) {}
			@Override public void keyTyped(KeyEvent e) {}
		});
		
		/**Button zum oeffnen einer Listenauswahl konstruieren*/
		btnOpenChoice.setEnabled(false);
		btnOpenChoice.setToolTipText("Öffnet die ausführliche Buchansicht des ausgewählten Rezepts");
		GridBagConstraints gbc_btnOpenChoice = new GridBagConstraints();
		gbc_btnOpenChoice.insets = new Insets(0, 0, 0, 5);
		gbc_btnOpenChoice.gridx = 1;
		gbc_btnOpenChoice.gridy = 1;
		add(btnOpenChoice, gbc_btnOpenChoice);
		btnOpenChoice.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent arg0) {
				try {
					new ShowRecipe(table.getTable().getSelectedRow(), 0);
				} catch (JDOMException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		btnOpenChoice.addKeyListener(new KeyListener() {
			@Override public void keyPressed(KeyEvent e) {
				try {
					if (e.getKeyCode() == KeyEvent.VK_ENTER)
						new ShowRecipe(table.getTable().getSelectedRow(), 0);
				} catch (JDOMException e1) {
					e1.printStackTrace();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			@Override public void keyReleased(KeyEvent e) {}
			@Override public void keyTyped(KeyEvent e) {}
		});
		/**Button zum bearbeiten einer Listenauswahl konstruieren*/
		btnEditChoice.setEnabled(false);
		btnEditChoice.setToolTipText("Hier kannst du das ausgewählte Rezept bearbeiten");
		GridBagConstraints gbc_btnEditChoice = new GridBagConstraints();
		gbc_btnEditChoice.insets = new Insets(0, 0, 0, 5);
		gbc_btnEditChoice.gridx = 2;
		gbc_btnEditChoice.gridy = 1;
		add(btnEditChoice, gbc_btnEditChoice);
		btnEditChoice.addActionListener(new ActionListener() {
			@Override public void actionPerformed(ActionEvent e) {
				try {
					new EditRecipe(table.getTable().getSelectedRow());
				} catch (HeadlessException e1) {
					e1.printStackTrace();
				} catch (JDOMException e1) {
					e1.printStackTrace();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		});
		btnEditChoice.addKeyListener(new KeyListener() {
			@Override public void keyPressed(KeyEvent e) {	
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					try {
						new EditRecipe(table.getTable().getSelectedRow());
					} catch (HeadlessException e1) {
						e1.printStackTrace();
					} catch (JDOMException e1) {
						e1.printStackTrace();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
			@Override public void keyReleased(KeyEvent e) {}
			@Override public void keyTyped(KeyEvent e) {}
		});
	}
	
	/**
	 * Liefert die Tabelle fuer die Rezeptuebersicht
	 * @return	Uebersichtstabelle
	 */
	public final static OverviewTable getTable() {
		return table;
	}
	
	/**
	 * Liefert den Loeschbutton fuer das Loeschen der Rezepte
	 * @return	JButton
	 */
	public final static JButton getbtn() {
		return btnDeleteChoice;
	}
	
	/**
	 * Konstruiert ein leeres Vorschau-Panel
	 * @throws JDOMException
	 * @throws IOException
	 */
	private void buildPreviewPanel() throws JDOMException, IOException {
		this.buildPreviewPanel(-1);
	}
	
	/**
	 * Konstruiert das Panel zur Anzeige der Vorschau
	 * @param selRow	Aktuell in der OverviewTable ausgewaehlte Zeile
	 * @throws JDOMException
	 * @throws IOException
	 */
	private void buildPreviewPanel(int selRow) throws JDOMException, IOException {
		previewPanel = new OverviewPanel_Preview(selRow);
		previewPanel.setToolTipText("Hier siehst du die wichtigsten Infos über das ausgewälte Rezept");
		previewPanel.setBorder(new TitledBorder(null, "Vorschau", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		previewPanel.setSize(300, 400);
		GridBagConstraints gbc_panel = new GridBagConstraints();
		gbc_panel.insets = new Insets(10, 0, 5, 0);
		gbc_panel.fill = GridBagConstraints.BOTH;
		gbc_panel.gridx = 4;
		gbc_panel.gridy = 0;
		add(previewPanel, gbc_panel);
	}
	
	/**
	 * Reset des Vorschau-Panels
	 * @throws JDOMException
	 * @throws IOException
	 */
	private void rebuildPreviewPanel() throws JDOMException, IOException {
		int checkedRows = table.getCheckedRowCount();
		int selectedRows = table.getTable().getSelectedRowCount();
		
		if (Config.debugMode())
			System.out.println("MouseListener - selRow: "+table.getTable().getSelectedRow());
		
		
		remove(previewPanel);
		revalidate();
		repaint();

		//Button-Aktivitaet festlegen
		if (checkedRows < 1) {
			if (selectedRows == 1) {
				btnOpenChoice.setEnabled(true);
				btnEditChoice.setEnabled(true);
				buildPreviewPanel(table.getTable().getSelectedRow());
			}
			else {//if (selectedRows != 1)
				btnOpenChoice.setEnabled(false);
				btnEditChoice.setEnabled(false);
				buildPreviewPanel();
			}
			btnDeleteChoice.setEnabled(false);
		}
		else if (checkedRows == 1) {
			if (selectedRows == 1) {
				btnOpenChoice.setEnabled(true);
				btnEditChoice.setEnabled(true);
				buildPreviewPanel(table.getTable().getSelectedRow());
			}
			else {//if (selectedRows != 1)
				btnOpenChoice.setEnabled(false);
				btnEditChoice.setEnabled(false);
				buildPreviewPanel();
			}
			btnDeleteChoice.setEnabled(true);
		}
		else { //if (checkedRows > 1)
			if (selectedRows == 1) {
				btnOpenChoice.setEnabled(true);
				btnEditChoice.setEnabled(true);
				buildPreviewPanel(table.getTable().getSelectedRow());
			}
			else {//if (selectedRows != 1)
				btnOpenChoice.setEnabled(false);
				btnEditChoice.setEnabled(false);
				buildPreviewPanel();
			}
			btnDeleteChoice.setEnabled(true);
		}
	}
}
